﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using AttributeRouting;
using AttributeRouting.Web.Mvc;
using Invoicing.Logic.Financial;
using Invoicing.Model.Financial;
using Invoicing.Model.Orders;
using Invoicing.Logic.Orders;
using Invoicing.Logic.Members;

namespace Invoicing.Web.Management.Areas.Financial.Controllers
{
    [RouteArea("Financial")]
    [RoutePrefix("Payment")]
    [Authorize]
    public class PaymentController : Controller
    {
        [Route("")]
        public ActionResult Index()
        {
            var Banks = BankLogic.GetBanks();
            ViewBag.Banks = Banks;
            return View();
        }

        [Route("VBankWater/{BankID:int}")]
        public ActionResult VBankWater(int BankID) 
        {
            ViewBag.BankID = BankID;
            return PartialView();
        }

        [Route("DealStatistic")]
        public ActionResult DealStatistic()
        {
            return View();
        }

        [Route("ExportBill")]
        public ActionResult ExportBill()
        {
            try
            {
                if (string.IsNullOrEmpty(Request.Form.Get("orderDateBefore")) || string.IsNullOrEmpty(Request.Form.Get("orderDateAfter")))
                    return Content("请选择日期");

                if (!string.IsNullOrEmpty(Request.Form.Get("customerID")))
                {
                    DealOrderQuery sea = new DealOrderQuery();
                    sea.CustomerID = int.Parse(Request.Form.Get("customerID"));
                    var customer = CustomerLogic.GetModel(sea.CustomerID, true);
                    if (customer != null)
                    {
                        var orderStatus = Request.Form.Get("orderStatus");
                        if (!string.IsNullOrEmpty(orderStatus))
                            sea.OrderStatus = orderStatus.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToArray();

                        var odb = Request.Form.Get("orderDateBefore");
                        if (!string.IsNullOrEmpty(odb))
                            sea.OrderDateBefore = DateTime.Parse(odb);
                        var oda = Request.Form.Get("orderDateAfter");
                        if (!string.IsNullOrEmpty(oda))
                            sea.OrderDateAfter = DateTime.Parse(oda);
                        var lst = DealOrderLogic.GetOrders(sea);

                        if (lst.Count > 0)
                        {
                            Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
                            workbook.Open(Server.MapPath("/RootFiles/Templates/Bill.xls"));
                            var sheet = workbook.Worksheets[0];
                            var cells = sheet.Cells;
                            var n = lst.Count + 3;

                            #region 表头
                            cells[0, 0].PutValue(string.Format("{0}对帐单", customer.ComplexName));
                            cells[1, 0].PutValue(string.Format("帐单期：{0:yyyy年MM月dd日} 至 {1:yyyy年MM月dd日}", sea.OrderDateBefore, sea.OrderDateAfter));
                            cells[1, 3].PutValue(string.Format("打印：{0:yyyy年MM月dd日}", DateTime.Now));
                            #endregion

                            #region 主数据
                            for (var i = 0; i < lst.Count; i++)
                            {
                                var order = lst[i];
                                if (i > 0)
                                {
                                    cells.InsertRow(3 + i);
                                    cells.CopyRow(cells, 3, 3 + i);
                                }
                                cells[3 + i, 0].PutValue(order.OrderNo);
                                cells[3 + i, 1].PutValue(order.NoteDate);
                                cells[3 + i, 2].PutValue(order.TotalMoney);
                                cells[3 + i, 3].PutValue(order.PaidMoney);
                            }
                            #endregion

                            ///填写余额
                            cells[n, 3].PutValue(customer.Balance);
                            //cells[n, 4].PutValue(-customer.Balance);
                            
                            #region 总计
                            cells[n+1, 2].Formula = string.Format("=Sum(C4:C{0})", n);
                            cells[n + 1, 3].Formula = string.Format("=Sum(D4:D{0})", n + 1);
                            cells[n+1, 4].Formula = string.Format("=C{0}-D{0}", n+2);
                            #endregion

                            #region 汇总公式
                            decimal unpay = 0;
                            var last = DealOrderLogic.GetOrders(new DealOrderQuery()
                            {
                                CustomerID = sea.CustomerID,
                                OrderDateAfter = sea.OrderDateBefore.Value.AddDays(-1),
                                OrderStatus = sea.OrderStatus
                            });
                            if (last.Count > 0)
                                unpay = last.Sum(p => p.TotalMoney - p.PaidMoney);
                            
                            cells[3 + n, 0].PutValue(string.Format("截止{0:yyyy年M月d日}以前的欠款为：", sea.OrderDateBefore));
                            cells[4 + n, 0].PutValue(string.Format("截止{0:yyyy年M月d日}总欠款为：", sea.OrderDateAfter));
                            cells[3 + n, 4].PutValue(unpay);
                            cells[4 + n, 4].Formula = string.Format("=E{0}+E{1}", n + 2, n + 4);
                            #endregion

                            var buffer = workbook.SaveToStream().ToArray();
                            return File(buffer, "application/octet-stream", string.Format("{0}对帐单.xls", customer.RealName));
                        }
                        else
                            return Content("没有交易记录");
                    }
                    else
                        return Content("不存在的客户");
                }else
                    return Content("请选择一个客户");
            }
            catch (Exception ex)
            {
                Common.Logger.Error("", ex);
                return Content(string.Format("服务器运行出错，请联系开发商。 <br /> {0}", ex.Message));
            }
        }
    }
}
